<template>
  <div class="app-container">
    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefresh"
          v-hasPermi="['sci:overview:query']"
        >刷新</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sci:overview:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getChartData"></right-toolbar>
    </el-row>

    <!-- 图表区域 - 第一行（两个图表） -->
    <el-row :gutter="20">
        
      <!-- 付款总额 -->
      <el-col :span="12" class="chart-container">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>付款总额（按研究方向）</span>
          </div>
          <div ref="paymentChart" style="height:400px;"></div>
        </el-card>
      </el-col>
      
     
      
      <!-- 固定资产本币原值 -->
      <el-col :span="12" class="chart-container">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>各研究方向2023-2025年度固定资产统计表</span>
          </div>
          <div ref="assetsChart" style="height:400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 - 第二行（三个图表） -->
    <el-row :gutter="20">
       <!-- 到货金额合计 -->
      <el-col :span="8" class="chart-container">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>到货金额合计（按研究方向）</span>
          </div>
          <div ref="arrivalChart" style="height:400px;"></div>
        </el-card>
      </el-col>
        <!-- 采购需求计划申请金额 -->
      <el-col :span="8" class="chart-container">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>采购需求计划申请金额（按研究方向）</span>
          </div>
          <div ref="demandChart" style="height:400px;"></div>
        </el-card>
      </el-col>
      
      <!-- 合同额 -->
      <el-col :span="8" class="chart-container">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>合同额（按研究方向）</span>
          </div>
          <div ref="contractChart" style="height:400px;"></div>
        </el-card>
      </el-col>
    
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getOverviewData } from "@/api/sci/equipoverview";

export default {
  name: "EquipmentOverview",
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      // 图表数据
      chartData: {
        demand: [],
        contract: [],
        payment: [],
        arrival: [],
        assets: []
      },
      // 图表实例
      demandChart: null,
      contractChart: null,
      paymentChart: null,
      arrivalChart: null,
      assetsChart: null
    };
  },
  mounted() {
    this.initCharts();
    this.getChartData();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    this.disposeCharts();
    window.removeEventListener('resize', this.resizeCharts);
  },
  methods: {
    // 初始化所有图表
    initCharts() {
      this.demandChart = echarts.init(this.$refs.demandChart);
      this.contractChart = echarts.init(this.$refs.contractChart);
      this.paymentChart = echarts.init(this.$refs.paymentChart);
      this.arrivalChart = echarts.init(this.$refs.arrivalChart);
      this.assetsChart = echarts.init(this.$refs.assetsChart);
    },
    
    // 销毁图表实例
    disposeCharts() {
      if (this.demandChart) this.demandChart.dispose();
      if (this.contractChart) this.contractChart.dispose();
      if (this.paymentChart) this.paymentChart.dispose();
      if (this.arrivalChart) this.arrivalChart.dispose();
      if (this.assetsChart) this.assetsChart.dispose();
    },
    
    // 重绘所有图表
    resizeCharts() {
      if (this.demandChart) this.demandChart.resize();
      if (this.contractChart) this.contractChart.resize();
      if (this.paymentChart) this.paymentChart.resize();
      if (this.arrivalChart) this.arrivalChart.resize();
      if (this.assetsChart) this.assetsChart.resize();
    },
    
    // 获取图表数据
    getChartData() {
      // 显示加载状态
      this.showChartLoading();
      
      getOverviewData().then(response => {
        this.chartData.demand = response.data.pocDemandDepAmountDatas || [];
        this.chartData.contract = response.data.constructInfoDepAmountDatas || [];
        this.chartData.payment = response.data.paymentInfoDepAmountDatas || [];
        this.chartData.arrival = response.data.goodsAcceptanceDepAmountDatas || [];
        this.chartData.assets = response.data.fixedAssetsDepAmountDatas || [];
        
        this.renderAllCharts();
      }).catch(() => {
        this.$modal.msgError("获取设备概览数据失败");
      });
    },
    
    // 显示所有图表的加载状态
    showChartLoading() {
      const loadingOptions = {
        text: '数据加载中...',
        color: '#1890ff',
        textColor: '#000',
        maskColor: 'rgba(255, 255, 255, 0.8)'
      };
      
      if (this.demandChart) this.demandChart.showLoading(loadingOptions);
      if (this.contractChart) this.contractChart.showLoading(loadingOptions);
      if (this.paymentChart) this.paymentChart.showLoading(loadingOptions);
      if (this.arrivalChart) this.arrivalChart.showLoading(loadingOptions);
      if (this.assetsChart) this.assetsChart.showLoading(loadingOptions);
    },
    
    // 渲染所有图表
    renderAllCharts() {
      this.renderChart(this.demandChart, this.chartData.demand, '采购需求计划申请金额');
      this.renderChart(this.contractChart, this.chartData.contract, '合同额');
      this.renderChart(this.paymentChart, this.chartData.payment, '付款总额');
      this.renderChart(this.arrivalChart, this.chartData.arrival, '到货金额合计');
      this.renderChart(this.assetsChart, this.chartData.assets, '固定资产本币原值');
    },
    
    // 渲染单个图表
    renderChart(chartInstance, data, title) {
      if (!data || data.length === 0) {
        chartInstance.showLoading({
          text: '暂无数据',
          color: '#1890ff',
          textColor: '#000',
          maskColor: 'rgba(255, 255, 255, 0.8)'
        });
        return;
      }
      
      chartInstance.hideLoading();
      
      // 提取部门名称和金额数据
      const departments = data.map(item => item.department);
      const amounts = data.map(item => item.totalAmount);
      
      // 按金额降序排序
      const sortedData = [...data].sort((a, b) => b.totalAmount - a.totalAmount);
      const sortedDepartments = sortedData.map(item => item.department);
      const sortedAmounts = sortedData.map(item => item.totalAmount);
      
      const option = {
        title: {
          text: title,
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c} 元',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: sortedDepartments,
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '金额(元)',
          nameTextStyle: {
            padding: [0, 30, 0, 0]
          }
        },
        series: [
          {
            name: title,
            type: 'bar',
            data: sortedAmounts,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            }
            // label: {
            //   show: true,
            //   position: 'top',
            //   formatter: '{c} 元'
            // }
          }
        ],
      };
      
      chartInstance.setOption(option);
    },
    
    /** 刷新按钮操作 */
    handleRefresh() {
      this.getChartData();
    },
    
    /** 导出按钮操作 */
    handleExport() {
      this.$modal.msgSuccess("导出功能开发中");
      // 实际导出代码需要根据需求实现
      // this.download('sci/overview/export', {}, `equipment_overview_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.chart-container {
  margin-bottom: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.el-card {
  border-radius: 8px;
}

.el-card__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
}
</style>